<template>
    <view class="remind-container">
      <!-- 提醒列表 -->
      <view class="remind-list">
        <view v-for="(item, index) in remindList" :key="item.id" class="remind-item">
          <view class="item-main">
            <view class="item-header">
              <text class="block">{{ item.block }}</text>
              <text class="time">{{ TimeformatTime(item.time) }}</text>
            </view>
  
            <view class="item-content">
              <text>{{ item.content }}</text>
            </view>
  
            <view class="item-footer">
              <view class="switch-wrap">
                <text class="switch-label">微信推送</text>
                <switch :checked="remindList[index].wechat" color="#07c160" @change="() => handleSwitchChange(item, index)" />
              </view>
            </view>
          </view>
  
          <!-- 删除按钮 -->
          <view class="delete-btn" @click.stop="handleDelete(item.id, index)">
            <uni-icons type="trash" size="20" color="#ff4d4f"></uni-icons>
          </view>
        </view>
      </view>
  
      <!-- 删除确认弹窗 -->
      <uni-popup ref="popup" type="dialog">
        <uni-popup-dialog type="warn" title="确认删除" content="确定要删除这条提醒吗？" @confirm="confirmDelete" />
      </uni-popup>
    </view>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue';
  import { useAppStore } from '@/stores/appStore';
  import { apiGetMention, apiDeleteMention, apiChangeMention } from '@/apis/apis';
  
  const appStore = useAppStore();
  const uid = ref(appStore.uid);
  const queryParam = { uid: uid.value, deleteDelay: 1 };
  
  const remindList = ref<any[]>([]);
  // 获取提醒列表
  const getRemindList = async () => {
    try {
      const res = await apiGetMention(queryParam);
      if (res.errCode === 200) {
        remindList.value = res.data.rows;
      } else {
        uni.showToast({ title: '获取提醒列表失败', icon: 'none' });
      }
    } catch (error) {
      console.error(error);
    }
  };
  
  getRemindList();
  
  // 删除相关逻辑
  const popup = ref<any>(null);
  const currentDeleteId = ref<string>('');
  const currentDeleteIndex = ref<number>(-1);
  
  const handleDelete = (id: string, index: number) => {
    currentDeleteId.value = id;
    currentDeleteIndex.value = index;
    popup.value.open();
  };
  
  const confirmDelete = async () => {
    if (currentDeleteIndex.value >= 0) {
      await apiDeleteMention({}, currentDeleteId.value);
      remindList.value.splice(currentDeleteIndex.value, 1);
      uni.showToast({ title: '删除成功', icon: 'success' });
    }
    popup.value.close();
  };
  
  // 切换处理
  const handleSwitchChange = async (item: any, index: number) => {
  try {
    const isTurningOn = ref(!item.wechat); // 用户意图打开还是关闭

    if (isTurningOn.value) {
      // 打开推送，需要请求订阅授权
      uni.requestSubscribeMessage({
        tmplIds: ['bvu0cbM_pxmjFs0sB95MMKImt8BsBELpLvnqrx93zU0'],
        success: async (res) => {
          console.log('授权结果:', res);

          const authResult = res['bvu0cbM_pxmjFs0sB95MMKImt8BsBELpLvnqrx93zU0'];

          if (authResult === 'accept') {
            // 用户同意
            await apiChangeMention({ wechat: true }, item.id);
            remindList.value[index].wechat = true;
            uni.showToast({ title: '开启推送成功', icon: 'success' });
          } else {
            // 用户拒绝
            remindList.value[index].wechat = false; // 复原开关
            uni.showToast({ title: '用户拒绝授权，推送未开启', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('请求订阅失败:', err);
          remindList.value[index].wechat = false; // 出现异常也要复原开关
          uni.showToast({ title: '请求失败，推送未开启', icon: 'none' });
          
          
        }
      });
    } else {
      // 关闭推送，直接修改
      await apiChangeMention({ wechat: false }, item.id);
      remindList.value[index].wechat = false;
      uni.showToast({ title: '已取消推送', icon: 'success' });
    }
    //逻辑修补
    if(isTurningOn.value==remindList.value[index].wechat&&remindList.value[index].wechat==true){
      remindList.value[index].wechat = !isTurningOn.value; // 复原开关
    }else{
      remindList.value[index].wechat = isTurningOn.value; // 复原开关
    }

  } catch (error) {
    console.error('切换推送失败:', error);
    uni.showToast({ title: '操作失败', icon: 'none' });
  }
  

};

  // 时间格式化
  const TimeformatTime = (time: string) => {
    const date = new Date(time);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };
  </script>
  
  <style scoped lang="scss">
  .remind-container {
    padding: 30rpx;
    background-color: #f7f8fa;
    min-height: 100vh;
  }
  
  .remind-list {
    margin-top: 20rpx;
  }
  
  .remind-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.06);
  }
  
  .item-main {
    flex: 1;
  }
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
  
    .block {
      font-size: 32rpx;
      font-weight: 600;
      color: #4a90e2;
    }
  
    .time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .item-content {
    font-size: 28rpx;
    color: #444;
    margin-bottom: 20rpx;
    line-height: 1.6;
  }
  
  .item-footer {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  
    .switch-wrap {
      display: flex;
      align-items: center;
      gap: 20rpx;
    }
  
    .switch-label {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .delete-btn {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20rpx;
    border-radius: 50%;
    background-color: #fff0f0;
  }
  </style>
  